package com.ruoyi.admin.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.admin.domain.*;
import com.ruoyi.admin.mapper.*;
import com.ruoyi.common.core.domain.entity.User;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.admin.service.IZhxCommentService;

/**
 * 评论管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-11-11
 */
@Service
public class ZhxCommentServiceImpl implements IZhxCommentService 
{
    @Autowired
    private ZhxCommentMapper zhxCommentMapper;

    @Autowired
    private ZhxBookMapper zhxBookMapper;

    @Autowired
    private ZhxJielongMapper zhxJielongMapper;

    @Autowired
    private ZhxLikeCommentMapper zhxLikeCommentMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private ZhxNoteMapper zhxNoteMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询评论管理
     * 
     * @param commentId 评论管理主键
     * @return 评论管理
     */
    @Override
    public ZhxComment selectZhxCommentByCommentId(Long commentId)
    {
        return zhxCommentMapper.selectZhxCommentByCommentId(commentId);
    }

    /**
     * 查询评论管理列表
     * 
     * @param zhxComment 评论管理
     * @return 评论管理
     */
    @Override
    public List<ZhxComment> selectZhxCommentList(ZhxComment zhxComment)
    {
        return zhxCommentMapper.selectZhxCommentList(zhxComment);
    }

    /**
     * 查询评论列表
     * 根据点赞量(likeNum)从高到低排序
     * @param zhxComment 评论
     * @return 评论
     */
    @Override
    public List<ZhxCommentTree> selectZhxCommentListByLike(ZhxComment zhxComment) {

        // 查询所有评论
        List<ZhxComment> zhxComments = zhxCommentMapper.selectZhxCommentListByLike(zhxComment);

        // 获取登录用户的id
        Long sysUserId = 0L;
        if (SecurityUtils.getUnUserId() != -1) {
            sysUserId = SecurityUtils.getUserId();
        }

        // 获取评论点赞信息
        Map<String, Long> zhxLikeCommentCache = new HashMap<>();
        if (redisCache.getCacheObject("zhxLikeCommentCache") != null) {
            zhxLikeCommentCache = redisCache.getCacheObject("zhxLikeCommentCache");
        } else {
            List<ZhxLikeComment> zhxLikeComments = zhxLikeCommentMapper.selectZhxLikeCommentList(new ZhxLikeComment());

            for (ZhxLikeComment zhxLikeComment : zhxLikeComments) {
                zhxLikeCommentCache.put(zhxLikeComment.getUserId() + "-" + zhxLikeComment.getCommentId(),1L);
            }
            redisCache.setCacheObject("zhxLikeCommentCache", zhxLikeCommentCache);
        }

        // 使用一个哈希表来存储评论的父子关系
        Map<Long, List<ZhxComment>> commentMap = new HashMap<>();

        // 遍历所有评论，将其按照父子关系分组，并设置用户信息
        for (ZhxComment comment : zhxComments) {
            // 从缓存中获取用户信息，如果没有则从数据库中查询并存入缓存
            User user = redisCache.getCacheObject("user:" + comment.getUserId());;
            if (user == null) {
                user = userMapper.selectUserByIdEasy(comment.getUserId());
                redisCache.setCacheObject("user:" + user.getUserId(), user);
            }
            comment.setSysUser(user);
            if (comment.getReplyUserId() != null) {
                User replyUser = redisCache.getCacheObject("user:" + comment.getReplyUserId());;
                if (replyUser == null) {
                    replyUser = userMapper.selectUserByIdEasy(comment.getReplyUserId());
                    redisCache.setCacheObject("user:" + replyUser.getUserId(), replyUser);
                }
                comment.setReplyUser(replyUser);
            }
            comment.setIsLike(zhxLikeCommentCache.get(sysUserId + "-" + comment.getCommentId()) == null ? 0 : 1);
            List<ZhxComment> children = commentMap.getOrDefault(comment.getCommentParentId(), new ArrayList<>());
            children.add(comment);
            commentMap.put(comment.getCommentParentId(), children);
        }

        // 创建一个空的结果列表
        ArrayList<ZhxCommentTree> zhxCommentTrees = new ArrayList<>();

        // 判断评论列表是否为空，如果为空，就直接返回空的结果列表
        if (zhxComments == null || zhxComments.isEmpty()) {
            return zhxCommentTrees;
        }

        if (commentMap.get(0L) != null) {
            // 遍历根评论，将其转换为树形结构，并添加到结果列表中
            for (ZhxComment comment : commentMap.get(0L)) {
                ZhxCommentTree zhxCommentTree = new ZhxCommentTree();
                BeanUtils.copyProperties(comment, zhxCommentTree);
                zhxCommentTrees.add(zhxCommentTree);
                buildTree(zhxCommentTree, commentMap);
            }
        }

        return zhxCommentTrees;
    }

    // 递归构建树形结构的辅助方法
    private void buildTree(ZhxCommentTree parent, Map<Long, List<ZhxComment>> commentMap) {
        List<ZhxComment> children = commentMap.get(parent.getCommentId());
        if (children != null && !children.isEmpty()) {
            for (ZhxComment child : children) {
                ZhxCommentTree childTree = new ZhxCommentTree();
                BeanUtils.copyProperties(child, childTree);
                parent.getChildren().add(childTree);
                buildTree(childTree, commentMap);
            }
        }
    }

    /**
     * 新增评论管理
     * 
     * @param zhxComment 评论管理
     * @return 结果
     */
    @Override
    public int insertZhxComment(ZhxComment zhxComment)
    {
        zhxComment.setCreateTime(DateUtils.getNowDate());
        return zhxCommentMapper.insertZhxComment(zhxComment);
    }

    /**
     * 新增评论管理
     * 增加book/jielong评论数量
     *
     * @param zhxComment 评论管理
     * @return 结果
     */
    @Override
    public int insertZhxCommentTodo(ZhxComment zhxComment)
    {
        zhxComment.setUserId(SecurityUtils.getUserId());
        zhxComment.setCreateTime(DateUtils.getNowDate());
        int i = zhxCommentMapper.insertZhxComment(zhxComment);

        // 如果是作品评论，增加作品评论数
        // 评论主体类型为1（作品）
        if (zhxComment.getComBodyType().equals("1")) {
            ZhxBook zhxBook = zhxBookMapper.selectZhxBookByBookId(zhxComment.getComBodyId());
            zhxBook.setCommentNum(zhxBook.getCommentNum() + 1);
            zhxBookMapper.updateZhxBook(zhxBook);
        }

        // 如果是接龙评论，增加接龙评论数
        // 评论主体类型为2（接龙）
        if (zhxComment.getComBodyType().equals("2")) {
            ZhxJielong zhxJielong = zhxJielongMapper.selectZhxJielongByJielongId(zhxComment.getComBodyId());
            zhxJielong.setCommentNum(zhxJielong.getCommentNum() + 1);
            zhxJielongMapper.updateZhxJielong(zhxJielong);

            // 新增评论互动消息
            ZhxNote zhxNote = new ZhxNote();
            // 信息类型（1接龙点赞 2评论点赞 3话题点赞 4评论 5回复）
            if (zhxComment.getReplyUserId() == null){
                zhxNote.setNoteType("4");
            } else {
                zhxNote.setNoteType("5");
            }
            zhxNote.setNoteBodyId(zhxComment.getCommentId());
            zhxNote.setUserId(zhxComment.getUserId());
            zhxNote.setToUserId(zhxJielong.getUserId());
            zhxNote.setIsRead("0");
            zhxNoteMapper.insertZhxNote(zhxNote);
        }



        return i;
    }

    /**
     * 修改评论管理
     * 
     * @param zhxComment 评论管理
     * @return 结果
     */
    @Override
    public int updateZhxComment(ZhxComment zhxComment)
    {
        zhxComment.setUpdateTime(DateUtils.getNowDate());
        return zhxCommentMapper.updateZhxComment(zhxComment);
    }

    /**
     * 批量删除评论管理
     * 
     * @param commentIds 需要删除的评论管理主键
     * @return 结果
     */
    @Override
    public int deleteZhxCommentByCommentIds(Long[] commentIds)
    {
        return zhxCommentMapper.deleteZhxCommentByCommentIds(commentIds);
    }

    /**
     * 删除评论管理信息
     * 
     * @param commentId 评论管理主键
     * @return 结果
     */
    @Override
    public int deleteZhxCommentByCommentId(Long commentId)
    {
        return zhxCommentMapper.deleteZhxCommentByCommentId(commentId);
    }

    /**
     * 获取作品数量
     */
    @Override
    public int getCommentNum() {
        return zhxCommentMapper.getCommentNum();
    }

    /**
     * 获取今日新增作品数量
     */
    @Override
    public int getCommentNumToday() {
        return zhxCommentMapper.getCommentNumToday();
    }
    
    
    
}
